# resources.py
from import_export import resources
from datetime import datetime
from . import models
import logging
from decimal import Decimal, InvalidOperation

logger = logging.getLogger(__name__)


class BookResource(resources.ModelResource):
    # def before_import_row(self, row, **kwargs):
    #     logger.info(f"Processing row: {row}")

    #     date_str = row.get('publish_date')
    #     if date_str:
    #         try:
    #             dt = datetime.strptime(date_str.strip(), '%Y/%m/%d').date()
    #             row['publish_date'] = dt.strftime('%Y-%m-%d')
    #             logger.info(
    #                 f"Converted publish_date to: {row['publish_date']}")
    #         except ValueError:
    #             try:
    #                 dt = datetime.strptime(date_str.strip(), '%Y-%m-%d').date()
    #                 row['publish_date'] = dt.strftime('%Y-%m-%d')
    #                 logger.info(
    #                     f"Converted publish_date to: {row['publish_date']}")
    #             except ValueError:
    #                 row['publish_date'] = None
    #                 logger.error(f"Failed to parse publish_date: {date_str}")

    #     price_str = row.get('price')
    #     if price_str:
    #         try:
    #             price = Decimal(price_str).quantize(Decimal('0.00'))
    #             row['price'] = str(price)
    #             logger.info(f"Converted price to: {row['price']}")
    #         except (InvalidOperation, TypeError):
    #             row['price'] = None
    #             logger.error(f"Failed to parse price: {price_str}")

    #     return row

    class Meta:
        model = models.Book
        exclude = ('id', 'created_at', 'updated_at',
                   'created_by', 'updated_by', 'active')
        import_id_fields = []  # 每次都新增


class BookChatpterResource(resources.ModelResource):

    class Meta:
        model = models.BookChatpter
        exclude = ('id', 'created_at', 'updated_at', 'created_by',
                   'updated_by', 'active', 'sort_order')  # 👈 只加这一行！忽略 id，自动生成


class BookAuthorResource(resources.ModelResource):
    class Meta:
        model = models.BookAuthor
        exclude = ('id', 'updated_at', 'updated_by',
                   'created_at', 'created_by')


class ListenBookResource(resources.ModelResource):
    class Meta:
        model = models.ListenBook
        exclude = ('id', 'updated_at', 'updated_by',
                   'created_at', 'created_by')
